package com.four.live.controller;

import com.four.live.config.CustomConfig;
import com.four.live.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author:wsy
 * @Date: 2021/12/28/9:01
 * @Description
 */
/**
 * 进行登录注册验证
 */
@RestController
public class ChatController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatController.class);

    /**
     * 用于记录已经登录的用户
     */
    public static final Map<String, String> USERS = new ConcurrentHashMap<>();

    /**
     * 进入欢迎页面
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * 进入登录页面
     * @param type
     * @param map
     * @return
     */
    @RequestMapping("/login/{type}")
    public String login(@PathVariable String type, Map<String, String> map) {
        System.out.println(type);
        System.out.println(map);
        map.put("type", type);
        return "login";
    }

    /**
     * 进入聊天页面
     * @param username
     * @param uuid
     * @return
     */
    @RequestMapping("/{username}/{uuid}")
    public String chat(@PathVariable String username, @PathVariable String uuid) {
        Map<String, Object> verifyMsg = new HashMap<>(4);
        System.out.println(username);
        System.out.println(uuid);
        // 将uuid作为用户访问非登录页面的验证
        verifyMsg.put(Util.STATE, Util.LOG_SUCCEED);
        verifyMsg.put(Util.USERNAME, uuid);
        USERS.put(username, uuid);
        LOGGER.info("{} login success!",username);
        if (uuid.equals(USERS.get(username))) {
            return "chat";
        }
        return "index";
    }

    /**
     * 进行登录校验
     * @param type
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/verify")
    @ResponseBody // 返回json字符串
    public Object verify(@RequestParam String type, @RequestParam String username, @RequestParam String password) {
        Map<String, Object> verifyMsg = new HashMap<>(4);
        try {
            String pwd = CustomConfig.USERS.getProperty(username);
            if ("login".equals(type)) {
                if (password.equals(pwd)) {
                    if (WebChat.CLIENTS.get(username) != null) {
                        LOGGER.info("{} has been login!",username);
                        verifyMsg.put(Util.STATE, Util.LOG_EXIST);
                    } else {
                        // 将uuid作为用户访问非登录页面的验证
                        String uuid = UUID.randomUUID().toString();
                        verifyMsg.put(Util.STATE, Util.LOG_SUCCEED);
                        verifyMsg.put(Util.USERNAME, uuid);
                        USERS.put(username, uuid);
                        LOGGER.info("{} login success!",username);
                    }
                } else {
                    verifyMsg.put(Util.STATE, Util.LOG_FAIL);
                    LOGGER.info("{} login failure!",username);
                }
            } else {
                if (pwd != null) {
                    verifyMsg.put(Util.STATE, Util.REG_FAIL);
                    LOGGER.info("{} has been register!",username);
                } else {
                    CustomConfig.USERS.setProperty(username, password);
                    try {
                        // 将新注册用户写入数据文件
                        CustomConfig.fwUser.write(username + "=" + password + System.lineSeparator());
                        CustomConfig.fwUser.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    verifyMsg.put(Util.STATE, Util.REG_SUCCEED);
                    LOGGER.info("{} register success!",username);
                }
            }
        } catch (Exception e) {
            verifyMsg.put(Util.STATE, Util.ERROR);
            verifyMsg.put("error", e.toString());
            LOGGER.error("An error occurred on the server!", e);
        }
        return verifyMsg;
    }
}
